import modal

app = modal.App("dict-queue-app")
image = modal.Image.debian_slim()

# 这里使用持久化的示例
my_queue = modal.Queue.from_name("job-queue", create_if_missing=True)
result_dict = modal.Dict.from_name("result-store", create_if_missing=True)

@app.function(image=image)
def worker():
    try:
        # 从队列中获取任务
        job_id, data = my_queue.get(timeout=5)
        print(f"处理任务 {job_id}...")
        # 将结果存入字典
        result_dict[job_id] = data * 2
    except modal.exception.TimeoutError:
        print("队列为空。")

@app.local_entrypoint()
def main():
    # 放入 5 个任务到队列
    for i in range(5):
        my_queue.put((f"job_{i}", i))
    
    # 启动 3 个 worker 并行处理
    worker.spawn(count=3)
    
    # 等待并检查结果
    import time
    time.sleep(10)
    for i in range(5):
        job_id = f"job_{i}"
        if job_id in result_dict:
            print(f"结果 {job_id}: {result_dict[job_id]}")